package com.servlet;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.config.AlipayConfig;
import com.entity.AlipayBean;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@WebServlet("/pay.do")
public class payServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String type = req.getParameter("type");
        switch (type) {
            case "pcPay":
                //获得初始化的AlipayClient
                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

                //设置请求参数
                AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
                alipayRequest.setReturnUrl(AlipayConfig.return_url);
                alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

                //商户订单号，商户网站订单系统中唯一订单号，必填
                String out_trade_no = new String(req.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //付款金额，必填
                String total_amount = new String(req.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
                //订单名称，必填
                String subject = new String(req.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
                //商品描述，可空
                String body = new String(req.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");

                alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                        + "\"total_amount\":\"" + total_amount + "\","
                        + "\"subject\":\"" + subject + "\","
                        + "\"body\":\"" + body + "\","
                        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
                //请求
                String result = null;
                try {
                    result = alipayClient.pageExecute(alipayRequest).getBody();
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                //输出
                out.println(result);
                break;
            case "phonePay":
                phonePay(req, resp, out);
                break;
        }
    }

    private void phonePay(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws UnsupportedEncodingException {
        if (req.getParameter("WIDout_trade_no") != null) {
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(req.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 订单名称，必填
            String subject = new String(req.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println(subject);
            // 付款金额，必填
            String total_amount = new String(req.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
            // 商品描述，可空
            String body = new String(req.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");
//            // 超时时间 可空
//            String timeout_express = "2m";
//            // 销售产品码 必填
//            String product_code = "QUICK_WAP_WAY";
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

            // 封装请求支付信息
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
//            model.setTimeoutExpress(timeout_express);
//            model.setProductCode(product_code);
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(AlipayConfig.notify_url);
            // 设置同步地址
            alipay_request.setReturnUrl(AlipayConfig.return_url);

            // form表单生产
            String form = "";
            try {
                // 调用SDK生成表单
                form = client.pageExecute(alipay_request).getBody();
                resp.setContentType("text/html;charset=" + AlipayConfig.charset);
                try {
                    resp.getWriter().write(form);//直接将完整的表单html输出到页面
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    resp.getWriter().flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    resp.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (AlipayApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}
